package com.lyh.hkcloud.util.http.listener.handler;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.lyh.hkcloud.MainActivity;
import com.lyh.hkcloud.util.base.JsonUtil;
import com.lyh.hkcloud.util.base.LogUtil;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import cz.msebera.android.httpclient.Header;
import org.json.JSONArray;
import org.json.JSONObject;

public class JsonHttpResponseHandlerImpl extends JsonHttpResponseHandler {

    private Context context;

    private JsonSuccessListener successListener;
    private JsonFailuredListener failuredListener;

    public JsonHttpResponseHandlerImpl(JsonSuccessListener successListener, JsonFailuredListener failuredListener, Context context) {
        this.successListener = successListener;
        this.failuredListener = failuredListener;
        this.context = context;
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        try {
            LogUtil.i("request", response.toString());
            if (context != null) {
                if ("0405".equals(JsonUtil.getString(response, "code"))) {
                    Intent intent = new Intent(context, Class.forName("com.lyh.hkcloud.activity.LoginActivity"));
                    context.startActivity(intent);
                    ((Activity) context).finish();
                    return;
                }
            }
            successListener.onRespone("", response);
        } catch (Exception e) {
            e.printStackTrace();
            failuredListener.onRespone(e.getMessage(), new JSONObject());
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
        failuredListener.onRespone(throwable.getMessage(), errorResponse);
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
        failuredListener.onRespone(throwable.getMessage(), new JSONObject());
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        failuredListener.onRespone(throwable.getMessage(), new JSONObject());
    }
}
